package com.xiongjie.ClusterCache;

import com.xiongjie.ClusterCache.Interface.IClusterCache;
import com.xiongjie.ClusterCache.entity.ClusterCacheEntity;
import com.xiongjie.ClusterCache.listener.ClusterCacheListener;
import com.xiongjie.ClusterCache.listener.ClusterCacheManagerListener;
import com.xiongjie.ClusterCache.service.SClusterCacheService;
import org.infinispan.Cache;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ClusterCacheApplication {

    static final String[] names = {"Rome", "Como", "Basel", "Bern", "London", "Newcastle", "Bucarest"};

    private final EmbeddedCacheManager cacheManager;
    private final IClusterCache iClusterCache;
    private Cache<String, ClusterCacheEntity> cache;

    private final ClusterCacheManagerListener cacheManagerListener;

    /**
     * 构造函数，创建缓存管理器和接口实现类
     */
    public ClusterCacheApplication() throws InterruptedException, IOException {

        cacheManager = new DefaultCacheManager(ClusterCacheApplication.class.getResourceAsStream("/cluster-infinispan.xml"));

        cacheManagerListener=new ClusterCacheManagerListener();
        cacheManager.addListener(cacheManagerListener);

        cache = cacheManager.getCache("clusterCache");
        cache.addListener(new ClusterCacheListener());

        iClusterCache = initClusterCacheService(cache);
    }

    /**
     * 销毁缓存管理器
     */
    public void shutdown() throws InterruptedException{
        cacheManager.stop();
    }

    /**
     * 初始化接口实现类，重要的数据，在系统环境变量中设置
     *
     * @param cache
     * @return
     */
    private IClusterCache initClusterCacheService(Cache<String, ClusterCacheEntity> cache) {
        return new SClusterCacheService("", cache);
    }

    /**
     * 父类引用调用子类对象
     */
    public void getClusterCacheEntity() {
        System.out.println("获取分布式缓存实体数据");

        long start = System.currentTimeMillis();

        for (String name : names) {
            ClusterCacheEntity entity = iClusterCache.getValueByName(name);
            System.out.println(String.format("%s - %s", name, entity));
        }

        System.out.println(String.format("获取分布式缓存实体数据花费时间：%dms", System.currentTimeMillis() - start));
    }

    public static void main(String[] args) throws Exception {
        ClusterCacheApplication app = new ClusterCacheApplication();

        app.getClusterCacheEntity();
        app.getClusterCacheEntity();
        TimeUnit.SECONDS.sleep(5);
        app.getClusterCacheEntity();

        app.shutdown();
    }

}
